package cn.exrick.xboot.modules.activiti.controller.business;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.exrick.xboot.base.XbootBaseController;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.modules.activiti.entity.business.MatterTemplate;
import cn.exrick.xboot.modules.activiti.service.business.MatterTemplateService;
import cn.exrick.xboot.modules.file.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lihuan
 */
@Slf4j
@RestController
@Api(description = "事项模版管理接口")
@RequestMapping("/xboot/matterTemplate")
@Transactional
public class MatterTemplateController extends XbootBaseController<MatterTemplate, String> {

	@Autowired
	private MatterTemplateService matterTemplateService;

	@Autowired
	private SecurityUtil securityUtil;
	
    @Autowired
    private FileService fileService;

	@Override
	public MatterTemplateService getService() {
		return matterTemplateService;
	}

	@RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
	@ApiOperation(value = "多条件分页获取")
	public Result<Page<MatterTemplate>> getByCondition(@ModelAttribute MatterTemplate matterTemplate,
			@ModelAttribute SearchVo searchVo, @ModelAttribute PageVo pageVo) {

		Page<MatterTemplate> page = getService().findByCondition(matterTemplate, searchVo,
				PageUtil.initPage(pageVo));
		return new ResultUtil<Page<MatterTemplate>>().setData(page);
	}

	@PostMapping("/saveFile")
	@ResponseBody
	public Result<Object> upload(String fileId) {
		String userId = securityUtil.getCurrUser().getId();
		MatterTemplate template = new MatterTemplate();
		if (fileId.isEmpty()) {
			return new ResultUtil<Object>().setErrorMsg("文件id不能为空");
		}
		cn.exrick.xboot.modules.file.entity.File dbFile = fileService.get(fileId);
		template.setFileId(dbFile.getId());
		template.setFileName(dbFile.getName());
		template.setFileSize(Double.valueOf(dbFile.getSize()));
		template.setStatus(0);
		String result = dbFile.getName().substring(dbFile.getName().length() - 3, dbFile.getName().length());
		if ("doc".equals(result.toLowerCase())) {
			List<String> list = testWord(dbFile.getUrl());
			if (list.size() == 0) {
				template.setStatus(1);
			}
//			// 接口调用先不实现
//            Boolean aBoolean = sendData.send(list, orderConfig,logger);
//            if(aBoolean ){
//            }else{
//            	template.setState(2);
//            }
		} else {
			template.setStatus(1);
		}
		/* 4.文件上传时间、上传人 */
		template.setCreateTime(new Date());
		template.setCreateBy(userId);
		template.setUpdateTime(new Date());
		template.setUpdateBy(userId);
		getService().save(template);
		return new ResultUtil<Object>().setData(null);
	}
	@PostMapping("/parseFile")
	@ResponseBody
	public Result<Object> parse(String fileId) {
		String userId = securityUtil.getCurrUser().getId();
		MatterTemplate template = new MatterTemplate();
		if (fileId.isEmpty()) {
			return new ResultUtil<Object>().setErrorMsg("文件id不能为空");
		}
		cn.exrick.xboot.modules.file.entity.File dbFile = fileService.get(fileId);
		List<String> list = testWord(dbFile.getUrl());
		return new ResultUtil<Object>().setData(list);
	}
	public List testWord(String path) {
		List list = new ArrayList();
		try {
			FileInputStream in = new FileInputStream(path);// 载入文档
			POIFSFileSystem pfs = new POIFSFileSystem(in);
			HWPFDocument hwpf = new HWPFDocument(pfs);
			Range range = hwpf.getRange();

			// 得到文档的读取范围
			TableIterator it = new TableIterator(range);
			// 迭代文档中的表格
			while (it.hasNext()) {
				Table tb = (Table) it.next(); // 迭代行，默认从0开始
				for (int i = 0; i < tb.numRows(); i++) {
					TableRow tr = tb.getRow(i);
					// 迭代列，默认从0开始
					for (int j = 0; j < tr.numCells(); j++) {
						TableCell td = tr.getCell(j);
						// 取得单元格 //取得单元格的内容
						for (int k = 0; k < td.numParagraphs(); k++) {
							Paragraph para = td.getParagraph(k);
							String s = para.text();
							list.add(s.replaceAll("\u0007", ""));
							System.out.println(s.replaceAll("\u0007", ""));
						} // end for
					} // end for
				} // end for
			} // end while
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return list;
		}
	}
}
